package com.am.mosl.cityandroid.login;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.am.mosl.cityandroid.R;
import com.am.mosl.cityandroid.activity.BaseActivity;
import com.am.mosl.cityandroid.bean.Account;
import com.am.mosl.cityandroid.bean.AccountBean;
import com.am.mosl.cityandroid.constant.HttpConstant;
import com.am.mosl.cityandroid.message.LoginMessage;
import com.am.mosl.cityandroid.util.SettingUtils;

import de.greenrobot.event.EventBus;

/**
 * @author 邓思宇 登入界面
 * 
 */
public class LoginActivity extends BaseActivity {

	private TextView forget;
	private TextView newAccount;
	private Button loginbtn;
	private EditText login_phone;
	private EditText login_code;
	public static Handler h;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.z_login_activity);

		h = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				switch (msg.what) {

				case 0:
					finish();
					break;

				}
			}

		};

		forget = (TextView) findViewById(R.id.Forget);
		newAccount = (TextView) findViewById(R.id.NewAccount);
		loginbtn = (Button) findViewById(R.id.login_btn);
		login_phone = (EditText) findViewById(R.id.login_phone);
		login_code = (EditText) findViewById(R.id.login_code);

		forget.setTextColor(Color.argb(155, 0, 0, 0)); // 文字透明度
		newAccount.setTextColor(Color.argb(255, 205, 50, 50)); // 文字透明度

		final Intent intent1 = new Intent(this, ForgetActivity.class);
		intent1.putExtra("FLAG", "0");

		final Intent intent2 = new Intent(this, ForgetActivity.class);
		intent2.putExtra("FLAG", "1");

		// 点击忘记密码
		forget.setClickable(true);
		forget.setFocusable(true);
		forget.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(intent1);

			}
		});

		// 点击新用户注册
		newAccount.setClickable(true);
		newAccount.setFocusable(true);
		newAccount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(intent2);
			}
		});

		// 点击登录按钮
		loginbtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				String loginphone = login_phone.getText().toString().trim();
				String logincode = login_code.getText().toString().trim();

				if (loginphone.equals("")) {
					Toast.makeText(LoginActivity.this, "手机号不能为空",
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (logincode.equals("")) {
					Toast.makeText(LoginActivity.this, "密码不能为空",
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (logincode.length() < 6) {
					Toast.makeText(LoginActivity.this, "密码长度不能小于6位",
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (!isMobile(loginphone)) {
					Toast.makeText(LoginActivity.this, "请输入正确的手机号",
							Toast.LENGTH_SHORT).show();
					return;
				}

				Login(loginphone, logincode);

			}

		});

		initBar();
	}

	protected void Login(final String loginphone, final String logincode) {
		// TODO Auto-generated method stub
		if (isNetworkAvailable(LoginActivity.this)) {
			FinalHttp finalHttp = new FinalHttp();
			AjaxParams params = new AjaxParams();
			params.put("telephone", loginphone);
			params.put("password", logincode);

			finalHttp.post(HttpConstant.Login, params,
					new AjaxCallBack<Object>() {
						@Override
						public boolean isProgress() {
							return super.isProgress();
						}

						@Override
						public void onSuccess(Object o) {
							super.onSuccess(o);
							try {
								JSONObject jsonObject = new JSONObject(o
										.toString());
								String status = (String) jsonObject
										.opt("status");
								String msg = (String) jsonObject.opt("msg");

								if (status.equals("1")) {
									
									String token = (String) jsonObject.opt("token");
									
									Account data1 = JSON.parseObject(
											jsonObject.toString(), Account.class);
									
									//设置别名用的
									JPushInterface.setAlias(LoginActivity.this, data1.getData().getUid(), null);
									
									saveUserInfo(token, data1, loginphone);
									
                                    LoginMessage message=new LoginMessage();
                                    message.setType(1);
                                    EventBus.getDefault().post(message);
									LoginActivity.this.finish();
									
								} else {
												
									Toast.makeText(
											LoginActivity.this,
											" 登录失败：" + msg
													,
											Toast.LENGTH_SHORT).show();

									return;

								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					});

		} else {
			Toast.makeText(LoginActivity.this, "网络未连接", Toast.LENGTH_SHORT)
					.show();
		}

	}

	private void saveUserInfo(String token, Account data, String telephone) {

		AccountBean accountBean = new AccountBean();
		accountBean.setToken(token);
		accountBean.setData(data.getData());
		accountBean.data.setPhone(telephone);
		SettingUtils.saveUserInfo(LoginActivity.this, accountBean);

	}

	private void initBar() {

		TextView title = (TextView) findViewById(R.id.tittle);
		title.setText("登录");

		View right_title = (TextView) findViewById(R.id.right_tittle);
		right_title.setVisibility(View.GONE);
	}

	// 点击返回
	public void BackToBack(View view) {
		this.finish();
	}

	/**
	 * 判断网络是否可用
	 * 
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager mgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 手机号验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isMobile(String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}
}